import { Category } from 'server/models/Category'
import { successResponse, errorResponse } from 'server/utils/response'

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event)
    const { name, description, color, icon } = body

    // 验证必需字段
    if (!name || !name.trim()) {
      return errorResponse('参数错误', '分类名称不能为空')
    }

    // 生成 slug
    const slug = name.toLowerCase()
      .replace(/\s+/g, '-')
      .replace(/[^\w\-]+/g, '')
      .replace(/\-\-+/g, '-')
      .replace(/^-+/, '')
      .replace(/-+$/, '')

    // 检查slug是否已存在
    if (await Category.isSlugExists(slug)) {
      return errorResponse('创建失败', '分类名称已存在，请使用其他名称')
    }

    const categoryData = {
      name: name.trim(),
      slug,
      description: description?.trim() || '',
      color: color || '#1890ff',
      icon: icon || 'fa:folder',
      status: 'active' as const,
      sort_order: 0
    }

    const categoryId = await Category.createCategory(categoryData)
    
    // 获取创建的分类信息
    const newCategory = await Category.getById(categoryId.toString())
    
    if (!newCategory) {
      return errorResponse('创建失败', '无法获取创建的分类信息')
    }

    // 格式化返回数据
    const formattedCategory = {
      id: newCategory.id?.toString() || '',
      name: newCategory.name,
      slug: newCategory.slug,
      description: newCategory.description || '',
      color: newCategory.color || '#1890ff',
      icon: newCategory.icon || 'fa:folder',
      postCount: 0,
      status: newCategory.status,
      createdAt: newCategory.created_at ? new Date(newCategory.created_at).toISOString().split('T')[0] : '',
      updatedAt: newCategory.updated_at ? new Date(newCategory.updated_at).toISOString().split('T')[0] : ''
    }

    return successResponse(formattedCategory, '分类创建成功')
  } catch (error) {
    console.error('创建分类失败:', error)
    return errorResponse('创建分类失败', error instanceof Error ? error.message : '未知错误')
  }
})